import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

export interface GroupBuy {
  id: string;
  title: string;
  description: string;
  originalPrice: number;
  groupPrice: number;
  minParticipants: number;
  maxParticipants: number;
  currentParticipants: number;
  participants: string[]; // 用户ID列表
  deadline: string;
  startTime: string;
  endTime: string;
  status: 'pending' | 'active' | 'success' | 'failed' | 'completed';
  creatorId: string;
  createdAt: string;
  updatedAt: string;
}

@Injectable()
export class GroupBuyService {
  private readonly groupBuysFile = path.join(process.cwd(), 'data', 'group-buys.json');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.groupBuysFile)) {
      fs.writeFileSync(this.groupBuysFile, JSON.stringify([]));
    }
  }

  private readGroupBuys(): GroupBuy[] {
    const data = fs.readFileSync(this.groupBuysFile, 'utf8');
    return JSON.parse(data);
  }

  private writeGroupBuys(groupBuys: GroupBuy[]): void {
    fs.writeFileSync(this.groupBuysFile, JSON.stringify(groupBuys, null, 2));
  }

  findAll(): GroupBuy[] {
    return this.readGroupBuys();
  }

  findById(id: string): GroupBuy | undefined {
    const groupBuys = this.readGroupBuys();
    return groupBuys.find(groupBuy => groupBuy.id === id);
  }

  create(groupBuyData: Omit<GroupBuy, 'id' | 'currentParticipants' | 'participants' | 'status' | 'createdAt' | 'updatedAt'>): GroupBuy {
    const groupBuys = this.readGroupBuys();
    const newGroupBuy: GroupBuy = {
      id: Date.now().toString(),
      ...groupBuyData,
      currentParticipants: 0,
      participants: [],
      status: 'pending',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    groupBuys.push(newGroupBuy);
    this.writeGroupBuys(groupBuys);
    return newGroupBuy;
  }

  update(id: string, groupBuyData: Partial<Omit<GroupBuy, 'id' | 'createdAt' | 'participants' | 'currentParticipants'>>): GroupBuy | null {
    const groupBuys = this.readGroupBuys();
    const index = groupBuys.findIndex(groupBuy => groupBuy.id === id);
    if (index === -1) return null;
    
    groupBuys[index] = {
      ...groupBuys[index],
      ...groupBuyData,
      updatedAt: new Date().toISOString(),
    };
    
    this.writeGroupBuys(groupBuys);
    return groupBuys[index];
  }

  delete(id: string): boolean {
    const groupBuys = this.readGroupBuys();
    const initialLength = groupBuys.length;
    const filteredGroupBuys = groupBuys.filter(groupBuy => groupBuy.id !== id);
    this.writeGroupBuys(filteredGroupBuys);
    return filteredGroupBuys.length !== initialLength;
  }

  joinGroupBuy(groupId: string, userId: string): GroupBuy | null {
    const groupBuys = this.readGroupBuys();
    const index = groupBuys.findIndex(gb => gb.id === groupId);
    
    if (index === -1) return null;
    
    const groupBuy = groupBuys[index];
    const now = new Date();
    
    // 检查团购状态
    if (groupBuy.status !== 'active') {
      return null;
    }
    
    // 检查是否已过截止日期
    if (new Date(groupBuy.deadline) < now) {
      return null;
    }
    
    // 检查是否已达到最大参与人数
    if (groupBuy.currentParticipants >= groupBuy.maxParticipants) {
      return null;
    }
    
    // 检查用户是否已参与
    if (groupBuy.participants.includes(userId)) {
      return null;
    }
    
    // 添加用户到参与者列表
    groupBuy.participants.push(userId);
    groupBuy.currentParticipants += 1;
    
    // 检查是否达到最低参与人数
    if (groupBuy.currentParticipants >= groupBuy.minParticipants) {
      groupBuy.status = 'success';
    }
    
    groupBuys[index] = groupBuy;
    this.writeGroupBuys(groupBuys);
    
    return groupBuy;
  }

  startGroupBuy(id: string): GroupBuy | null {
    const groupBuys = this.readGroupBuys();
    const index = groupBuys.findIndex(gb => gb.id === id);
    
    if (index === -1) return null;
    
    const groupBuy = groupBuys[index];
    const now = new Date();
    
    // 检查开始时间
    if (new Date(groupBuy.startTime) > now) {
      return null;
    }
    
    groupBuy.status = 'active';
    groupBuys[index] = groupBuy;
    this.writeGroupBuys(groupBuys);
    
    return groupBuy;
  }

  getUserGroupBuys(userId: string): GroupBuy[] {
    const groupBuys = this.readGroupBuys();
    return groupBuys.filter(gb => gb.participants.includes(userId));
  }
}